﻿using System.Security.Claims;
using BoYuanCore.Framework;
using BoYuanCore.WebForm.Code;
using FineUICore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Serilog;

namespace BoYuanCore.WebForm.Pages.Admin
{
    [AllowAnonymous]
    public partial class LoginModel : BaseModel
    {
        protected async Task Page_LoadAsync(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
            else
            {
                string arg = GetRequestEventArgument(); 
                if (arg == "LoginEvent")
                {
                    string username = u.Text.Trim();
                    string pwd = p.Text.Trim();
                    try
                    {
                        pwd = Security.MD5Helper.GetMd5Pwd(pwd);

                        var admin = await DB.Select<Entities.SysAdmin, Entities.SysRole>()
                            .LeftJoin((a, r) => a.RoleID == r.ID)
                            .Where((a, r) => r.IsDel == false && a.IsDel == false && a.LoginName == username && a.Password == pwd)
                            .FirstAsync((a, r) => a);

                        if (admin == null)
                        {
                            await DBServices.SysLoginLog.AddLoginLogAsync(username, pwd, Entities.EnumClass.SysLoginLog.LoginState.登录失败);
                            AlertError("用户名或密码错误!");
                            return;
                        }

                        await DBServices.SysLoginLog.AddLoginLogAsync(username, pwd, Entities.EnumClass.SysLoginLog.LoginState.登录成功, userid: admin.ID);

                        //身份信息
                        var claims = new[] {
                            //new Claim("name", string.IsNullOrEmpty(admin.RealName)?admin.LoginName:admin.RealName),
                            new Claim("userid", admin.ID.ToString())
                        };
                        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                        ClaimsPrincipal userInfo = new ClaimsPrincipal(claimsIdentity);
                        await HttpContext.SignInAsync(
                            CookieAuthenticationDefaults.AuthenticationScheme,
                            userInfo,
                            new AuthenticationProperties()
                            {
                                //https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/cookie?view=aspnetcore-2.1&tabs=aspnetcore2x
                                //https://www.cnblogs.com/sheldon-lou/p/9545726.html
                                //IsPersistent = true,//是否为永久性cookie(永不过期)。ExpiresUtc设置会使IsPersistent=true失效
                                ExpiresUtc = DateTime.UtcNow.AddHours(1)//默认1个小时过期(每次页面刷新会增加失效时间,跟session机制很像)
                            });

                        Response.Redirect("admin/index");
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            await DBServices.SysLoginLog.AddLoginLogAsync(username, pwd, Entities.EnumClass.SysLoginLog.LoginState.登录异常, ex.Message);
                        }
                        catch (Exception exception)
                        {
                            Log.Error("");
                        }
                        AlertError("系统执行错误，请重试！" );
                    }
                }
            }
            
        }

  
    }
}